// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import ComponentBase from "../../../general/Script/component/ComponentBase";
import DataMgr from "../../../general/Script/mgr/dataManager";
import GameMgr from "../../../general/Script/mgr/gameManager";
import NativeMgr from "../../../general/Script/mgr/nativeManager";
import NetMgr from "../../../general/Script/mgr/netManager";



const { ccclass, property } = cc._decorator;

@ccclass
export default class AdTestLayer extends ComponentBase {

    adButtons: cc.Node = null;
    infoNode: cc.Node = null;
    infoLab: cc.Node = null;
    phoneInfo: cc.Node = null;
    adInfo: cc.Node = null;
    isClick: boolean = false;
    @property(cc.Node)
    configManagerNode: cc.Node = null;

    bannerShowTime: number = 60;

    schedules: any = {};


    deviceId: string = '';
    appId: string = '';
    channel: string = "";


    adInfoJson: any = {
        totalfinish: 0,
        totalClick: 0,
        finish: 0,
        click: 0,
        totalMoney: 0,
        money: 0,
        reward: 0
    }

    onLoad(): void {
        super.onLoad()


    }
    start() {
        this.initEvent();
        this.initData()
    }

    initEvent() {
        cc.systemEvent.on('openAds', (data) => {
            console.log('openAds = ', Number(data));
            GameMgr.Ins().showMsg('获得的积分' + data);
            // this.changeDataByType('openAds',Number(data));
            this.refreshButtons(true);
            this.httpRequest({ event: 'finish', source: NativeMgr.Ins().channel(), worth: data })
        }, this);

        cc.systemEvent.on('bannerAds', (data) => {
            console.log('bannerAds = ', Number(data));
            GameMgr.Ins().showMsg('获得的积分' + data);
            // this.changeDataByType('bannerAds',Number(data));
            // this.scheduleOnce(()=>{
            //     NativeMgr.Ins().delBottomBannerAds()
            // },this.bannerShowTime);
            this.refreshButtons(true);
            this.httpRequest({ event: 'finish', source: NativeMgr.Ins().channel(), worth: data })
        }, this);

        cc.systemEvent.on('rewardAds', (data) => {
            console.log('rewardAds = ', Number(data));
            GameMgr.Ins().showMsg('获得的积分' + data);
            // this.changeDataByType('rewardAds',Number(data));
            this.refreshButtons(true);
            this.httpRequest({ event: 'finish', source: this.channel, worth: data })
            this.httpRequest({ event: 'reward', source: this.channel })
        }, this);

        cc.systemEvent.on('fullAds', (data) => {
            console.log('fullAds = ', Number(data));
            GameMgr.Ins().showMsg('获得的积分' + data);
            this.refreshButtons(true);
            this.httpRequest({ event: 'finish', source: this.channel, worth: data })
        }, this);

        cc.systemEvent.on('expressAds', (data) => {
            console.log('expressAds = ', Number(data));
            GameMgr.Ins().showMsg('获得的积分' + data);
            this.httpRequest({ event: 'finish', source: this.channel, worth: data })
            this.refreshButtons(true);
        }, this);


        cc.systemEvent.on("RewardWaitting", () => {
            this.infoLab.getComponent(cc.Label).string = '视频广告正在加载中。。。';
            this.refreshButtons(false);
        }, this);
        cc.systemEvent.on("onAdFailed", (data) => {
            this.infoLab.getComponent(cc.Label).string = `视频加载失败，类型:${data}`;
            this.refreshButtons(true);
        }, this);

        cc.systemEvent.on("onAdClick", (data) => {
            this.httpRequest({ event: 'click', source: this.channel })
        }, this);


    }

    refreshButtons(active) {
        this.refreshButton('openAds', active);
        this.refreshButton('bannerAds', active);
        this.refreshButton('rewardAds', active);
        this.refreshButton('fullAds', active);
        this.refreshButton('expressAds', active);


    }

    refreshButton(type, active) {
        const button = this.adButtons.getChildByName("BM_" + type);
        button.getComponent(cc.Button).interactable = active;
    }



    async initData() {


        const deviceId = NativeMgr.Ins().deviceId();
        const appId = NativeMgr.Ins().appId();
        const channel = NativeMgr.Ins().channel();

        this.phoneInfo.getComponent(cc.Label).string = `deviceId:${deviceId}\nappId:${appId}`;

        this.deviceId = deviceId
        this.appId = appId;
        this.channel = channel;
        this.refreshAdInfo()

    }



    httpRequest(options) {
        options.appid = this.appId;
        options.unionid = this.deviceId;
        options.worth = Number(options.worth) > 0 ? Number(options.worth) : 0

        if (this.isClick && options.event === 'click') {
            return;
        }
        console.log('httpSend = ', options);
        NetMgr.Ins().servo.post('/payment/advertising/transaction', options, true);

        if (options.event === 'finish') {
            this.adInfoJson.finish++;
            this.adInfoJson.totalMoney += options.worth / 100000;
            this.adInfoJson.totalfinish++;
            this.isClick = false;
            this.adInfoJson.money += options.worth / 100000;
        } else if (options.event === 'click') {
            this.adInfoJson.click++;
            this.adInfoJson.totalClick++;
            this.isClick = true;
        } else if (options.event === 'reward') {
            this.adInfoJson.reward++;
        }
        this.refreshAdLabels();
    }


    async refreshAdInfo() {
        const begin = DataMgr.Ins().formatData();
        const end = DataMgr.Ins().formatData(1);

        const infoTotal = await NetMgr.Ins().servo.get(`/payment/advertising/aggs?appid=${this.appId}&begin=${begin}&end=${end}`);
        console.log('infoTotal = ', infoTotal);
        if (infoTotal.status === 200) {
            const arr = infoTotal.body;
            for (let i in arr) {
                const item = arr[i];
                if (item.event === 'finish' && item.source === this.channel) {
                    this.adInfoJson.totalfinish = item.count;
                    this.adInfoJson.totalMoney = item.total / 100000;
                } else if (item.event === 'click' && item.source === this.channel) {
                    this.adInfoJson.totalClick = item.count;
                }
            }
        }

        const info = await NetMgr.Ins().servo.get(`/payment/advertising/aggs?appid=${this.appId}&unionid=${this.deviceId}&begin=${begin}&end=${end}`);
        console.log('info = ', info);
        if (info.status === 200) {
            const arr = info.body;
            for (let i in arr) {
                const item = arr[i];
                if (item.event === 'finish' && item.source === this.channel) {
                    this.adInfoJson.finish = item.count;
                    this.adInfoJson.money = item.total / 100000;
                } else if (item.event === 'click' && item.source === this.channel) {
                    this.adInfoJson.click = item.count;
                } else if (item.event === 'reward' && item.source === this.channel) {
                    this.adInfoJson.reward = item.count;
                }
            }
        }


        console.log('info = ', this.adInfoJson);

        this.refreshAdLabels()

    }

    refreshAdLabels() {
        this.adInfo.getComponent(cc.Label).string = `总完成:${this.adInfoJson.totalfinish}，总点击:${this.adInfoJson.totalClick}，总点击率:${(this.adInfoJson.totalClick / this.adInfoJson.totalfinish).toFixed(2)}，今日总获得:${this.adInfoJson.totalMoney.toFixed(2)}元\n单号完成:${this.adInfoJson.finish}次，激励:${this.adInfoJson.reward}次，点击:${this.adInfoJson.click}次，点击率:${(this.adInfoJson.click / this.adInfoJson.finish).toFixed(2)}，获得:${this.adInfoJson.money.toFixed(2)}元`
    }



    openAdsCallBack() {
        console.log('openAdsCallBack');
        NativeMgr.Ins().showOpenAds();
    }


    bannerAdsCallBack() {
        console.log('bannerAdsCallBack');
        NativeMgr.Ins().showBottomBannerAds();
    }

    rewardAdsCallBack() {
        console.log('rewardAdsCallBack');
        NativeMgr.Ins().showAds(1);
    }

    fullAdsCallBack() {
        console.log('rewardAdsCallBack');
        NativeMgr.Ins().showFullAds();
    }

    expressAdsCallBack() {
        console.log('rewardAdsCallBack');
        NativeMgr.Ins().showExpressAds(0);
    }


    refreshCallBack() {
        this.refreshAdInfo();

    }



    getSettingsByType(type: string) {
        const info = {
            count: 0,
            interval: 0,
        }

        const countNode = this.configManagerNode.getChildByName(type).getChildByName('count');
        const timeNode = this.configManagerNode.getChildByName(type).getChildByName('time');
        info.count = Number(countNode.getComponent(cc.EditBox).string);
        info.interval = Number(timeNode.getComponent(cc.EditBox).string);
        return info;
    }
    saveSettingCallBack() {


    }


    closeBtnCallBack() {
        this.node.removeFromParent(true);
        this.node.destroy()
    }

    onDestroy(): void {
        super.onDestroy();
        this.unscheduleAllCallbacks();
        cc.systemEvent.targetOff(this);
        NativeMgr.Ins().delBottomBannerAds()
    }

}
